package com.googlecode.horncomb.orm.ibatis;

import java.beans.PropertyDescriptor;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.BeanUtils;
import org.springframework.util.Assert;

import com.googlecode.horncomb.bean.filter.ConditionSet;
import com.googlecode.horncomb.bean.filter.SimpleMapConditionSet;

@SuppressWarnings("unchecked")
abstract class SqlMapEntityDaoUtil {
	/**
	 * @param example
	 * @return
	 */
	public static ConditionSet convertExampleToConstraints(Object example) {
		SimpleMapConditionSet qry = new SimpleMapConditionSet();
		qry.getConstraintsMap().putAll(convertObjectToMap(example));
		return qry;
	}

	/**
	 * @param entity
	 * @return
	 */
	public static Map<String, Object> convertObjectToMap(Object entity) {
		Assert.notNull(entity);
		Map map = new HashMap();
		PropertyDescriptor[] pd = BeanUtils.getPropertyDescriptors(entity
				.getClass());
		for (int i = 0; i < pd.length; i++) {
			try {
				map.put(pd[i].getDisplayName(), pd[i].getReadMethod().invoke(
						entity, new Object[] {}));
			} catch (Exception e) {
				//				this.logger.debug("通过属性的只读方法获取数失败", e); //$NON-NLS-1$
			}
		}
		return map;
	}
}
